import { discussStore } from '../stores/discuss'
export default class {
    count = 0//重连次数
    wsflag = false//判断是否连接成功
    discuss = discussStore()
    ws: any = null
    createWs() {
        if (!window.WebSocket) {
            return alert('您的浏览器不支持WebSocket');
        }
        this.ws = new WebSocket("ws://127.0.0.1:3000");
        this.ws.onopen = () => {
            console.log("ws连接成功");
            this.wsflag = true
        }
        this.ws.onclose = () => {
            console.log("服务端连接失败,正在尝试重新连接..." + this.count);
            setTimeout(() => {
                this.createWs()
                this.count++
            }, 2000);
        }
        //服务端发送过来的数据
        this.ws.onmessage = (wsdata: any) => {
            const data = JSON.parse(JSON.parse(wsdata.data))
            console.log("data is ", data);
            if (data.flag === 'reply') {
                this.discuss.replyComment = data.data
                return console.log("回复", data.data);
            }
            if (data.flag === 'comment') {
                this.discuss.userComment = data.data
                return console.log("评论", data.data);
            }

        }
        //发送数据
    }
    send(data: any) {
        console.log("ws data", data, this.wsflag);
        if (this.wsflag) {
            try {
                this.ws.send(JSON.stringify(data));
            } catch (e) {
                this.ws.send(data);
            }
        } else {
            setTimeout(() => {
                this.send(data);
            }, 1000);
        }
    }
}